package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.entity.Activity;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 活动管理业务层实现类
 *
 * @Author:Mr.m
 * @Date: 2025-10-09 15:56
 * @Description:
 */
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    //根据指定类型的查询活动
    @Override
    public List<Activity> queryActivityByType(Integer type) {
        return activityMapper.queryActivityByType(type);
    }

    //根据id删除活动
    @Override
    public void deleteById(Integer id) {
        activityMapper.deleteById(id);
    }

    //修改活动内容
    @Override
    public void update(Activity activity) {
        //校验参数
        boolean hasNull = BeanUtil.hasNullField(activity, "id", "discount", "voucher", "createTime", "updateTime");
        if (hasNull){
            throw new RuntimeException("参数错误");
        }
        // 添加更新时间
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);
    }

    //根据id查询活动（数据回显）
    @Override
    public Activity queryActivityById(Integer id) {
        return activityMapper.queryActivityById(id);
    }

    //新增活动
    @Override
    public void addActivity(Activity activity) {
        //校验参数
        boolean hasNull = BeanUtil.hasNullField(activity, "id", "discount", "voucher", "createTime", "updateTime");
        if (hasNull){
            throw new RuntimeException("参数错误");
        }

        //补全参数
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        //插入数据
        activityMapper.insert(activity);
    }

    //分页查询所有活动
    @Override
    public PageResult<Activity> page(Integer channel, Integer type, Integer status, Integer page, Integer pageSize) {

        //开始分页
        PageHelper.startPage(page, pageSize);

        //执行查询
        List<Activity> activitys = activityMapper.selectByPage(channel, type, status);

        //获取分页信息
        Page<Activity> pageResult = (Page<Activity>) activitys;

        //封装成 pageResult 对象
        return PageResult.<Activity>builder()
                .total(pageResult.getTotal())
                .rows(pageResult.getResult())
                .build();
    }
}
